package org.example.backend.demos.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;

@Configuration
public class CorsConfig {
    List<String> allowedOrigins = List.of("http://localhost:5174");
    List<String> Methods = List.of("GET", "POST", "PUT", "DELETE");

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        // 创建对象，定义规则
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(allowedOrigins);
        configuration.setAllowedMethods(Methods);
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);
        // 创建源对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册到源
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
